Problem:
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. 对于两个排好序的数组,如何进行合并呢? 主要思想是定义两个指针,数组从尾到头比较,直到有一个数组到头,如果B到头,则返回,如果A到头,继续将B内的元素放到A的前面部分
1234567891011121314151617181920212223242526 public class solution {public static void merge(int A[], int m, int B[], int n) {int i=m-1;int j=n-1;int newlen=m+n-1;while(i>=0&&j>=0){ //loop until one array get to the headif(A[i]<B[j])A[newlen--]=B[j--];elseA[newlen--]=A[i--];}while(j>=0) //if A reaches its head, copy the remained entrys of B to newA;A[newlen--]=B[j--];//if B reaches its head, there' s no need to copy the remained entrys of A to newA;}public static void main(String[] args) {int[] A =new int[10];A[0]=7;A[1]=9;A[2]=10;int[] B = {2,5,6};merge(A,3,B,3);for(int entry :A)System.out.print(entry+" ");}}